using Godot;
using System;
using CSharpLearning.scripts.generated;

public partial class Bird : RigidBody2D
{
    // 小鸟的跳跃力
    [Export]
    private float _mJumpForce = 300;
    // 小鸟的水平速度
    [Export]
    private float _mHorizontalSpeed = 200;
    // 小鸟的旋转速度
    [Export]
    private float _mRotateSpeed = 300;
    // 小鸟的保持角度时间
    [Export]
    private float _mKeepAngleTime = 0.2f;
    // 小鸟的跳跃cd
    [Export]
    private float _mJumpCd = 0.5f;
    
    // 跳跃后开始旋转的计时器
    private Timer _mRoateTimer;
    // 控制小鸟跳跃cd的计时器
    private Timer _mJumpCdTimer;
    
    // 是否可以开始旋转
    private bool IsCanRoate = true;
    // 是否可以跳跃
    private bool IsCanJump = true;
    
    public override void _Ready()
    {
        base._Ready();
        // 创建小鸟的旋转计时器
        _mRoateTimer = new Timer();
        _mRoateTimer.OneShot = true;
        _mRoateTimer.WaitTime = _mKeepAngleTime;
        AddChild(_mRoateTimer);
        
        _mJumpCdTimer = new Timer();
        _mJumpCdTimer.OneShot = true;
        _mJumpCdTimer.WaitTime = _mJumpCd;
        AddChild(_mJumpCdTimer);
        
        _mRoateTimer.Timeout += () =>
        {
            IsCanRoate = true;
        };
        _mJumpCdTimer.Timeout += () =>
        {
            IsCanJump = true;
        };
    }

    public override void _Process(double delta)
    {
        base._Process(delta);
        // 处理输入
        HandleInput();
    }

    public override void _PhysicsProcess(double delta)
    {
        base._PhysicsProcess(delta);
        // 处理旋转
        if (IsCanRoate)
        {
            var targetRotation = Rotation + _mRotateSpeed * (float)delta;
            // 限制最小角度为-90度
            targetRotation = float.Clamp(targetRotation, -Single.Pi/3, Single.Pi/3);
            Rotation = targetRotation;
            
        }
        else
        {
            // 始终为60度
            Rotation =-Single.Pi / 3;
        }
    }

    private void HandleInput()
    {
        // 处理跳跃
        if (Input.IsActionJustPressed(Actions.FlappyJump) && IsCanJump)
        {
            IsCanJump = false;
            IsCanRoate = false;
            // 跳跃
            ApplyCentralImpulse(new Vector2(0, -_mJumpForce));
            // 开始旋转
            _mRoateTimer.Start();
            // 开始跳跃cd
            _mJumpCdTimer.Start();
        }
    }
}